const fs = require('fs');
const path = require('path');
const { ErrorModel, SuccessModel } = require('../../model/responseMode');
const MusicLrcModel = require('../../model/music/musicLrcModel');
const MusicText = require('../../model/music/musicTextModel');
const filePath = fs.readdirSync("src")

// 上传歌词列表
const addMusiclrc = async() => {
  let musicLrcList = []
  const data = fs.readdirSync("./src/statics/musicLrc");

  data.forEach(async (item) => {
    let dataItem = item
    let index = item.lastIndexOf('.');  // 分割
    let name = item.substring(0, index);
    let list = name.split(` - `);
    let singer = list[0].trim();    // 歌手
    let songName = list[1].trim();  // 歌曲
    let fileType = item.substring(index, item.length);  // 文件类型
    let path = 'statics/musicLrc/';
    let original = item
    let obj = {
      singer,
      music_name: songName,
      music_lrc: name,
      file_type: fileType,
      path,
      original
    }
    // 将歌词列表入库
    musiclrc = new MusicLrcModel(obj)
    try {
      await musiclrc.save()
    } catch (error) {
      console.log(error)
    }
  });
  return {
    message: 'ok'
  }
}

// 上传歌词文件
const addMusiclrcText = async() =>{
  let url = 'src/statics/musicLrc/'
  let absolutePath = fs.realpathSync(url)
  let data = fs.readdirSync(absolutePath)

  data.forEach(async e => {
    let textPath = path.join(absolutePath, e);
    let text = fs.readFileSync(textPath).toString();

    let item = e
    let index = item.lastIndexOf('.')
    let name = item.substring(0, index);
    let list = name.split(` - `);

    let singer = list[0].trim();
    let music_name = list[1].trim();
    let file_type = item.substring(index, item.length);
    let original = e

    let obj = {
      singer,
      music_name,
      file_type,
      original,
      text
    }
    let musicText = new MusicText(obj)

    try {
      await musicText.save()
    } catch (error) {
      console.log(error)
    }

  });

  return {
    message: 'ok'
  }
}

// 更新歌词文件
const updataMusiclrcText = async() => {
  // let url = 'src/statics/musicLrc/'
  // let absolutePath = fs.realpathSync(url)
  // let data = fs.readdirSync(absolutePath)
  
  let data = await MusicText.find();
  data.forEach(async e => {
    const name = e.original.substring(0, e.original.lastIndexOf('.'))
    await MusicText.updateMany({_id: e._id }, {$set: {name: name } });
  })

  return {
    message: 'ok'
  }
}

module.exports = {
  addMusiclrc,
  addMusiclrcText,
  updataMusiclrcText
}